using System;
using System.Reflection;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using ACM.cmsarea08;
using ACM.cmsarea08.mainconfiguration;



namespace ACM.cmsarea08.Core {
	public class TextFileHandler :  IHttpAsyncHandler { //IHttpHandler

       public bool IsReusable { get { return true; } }
        
     public void ProcessRequest(System.Web.HttpContext contesto)
        {
			// non usato
        }
		
	  public IAsyncResult BeginProcessRequest(HttpContext ctx, AsyncCallback cb, object obj)
	  {
	    AsyncTextFileState reqState = new AsyncTextFileState(ctx, cb, obj);
	    AsyncTextFileRequest ar = new AsyncTextFileRequest(reqState);
	    ThreadStart ts = new ThreadStart(ar.ProcessRequest);
	    Thread t = new Thread(ts);
	    t.Start();
	    return reqState;
	  }
        
	  public void EndProcessRequest(IAsyncResult ar)
	  {
	    AsyncTextFileState ars = ar as AsyncTextFileState;
	    if (ars != null)
	    {
	     // Clean Up
	    }
	  }      
        
	}
	
	public class AsyncTextFileState : IAsyncResult {
		
		internal HttpContext _ctx;
		internal AsyncCallback _cb;
		internal object _dati;
		private bool _iscompleted = false;
		private ManualResetEvent _callCompleteEvent = null;
		
		public AsyncTextFileState(HttpContext ctx, AsyncCallback cb, object dati) {
			_ctx = ctx;
			_cb = cb;
			_dati = dati;
			
		}
		internal void CompleteRequest() {
			_iscompleted = true;
			lock(this) {
				if(_callCompleteEvent!=null) {
					_callCompleteEvent.Set();
				}
				 if (_cb != null)
				 	_cb(this);
			}
		}
		public object AsyncState {
			get { return _dati; }
		}
		public bool CompletedSynchronously {
			get { return false; }
		}
		public bool IsCompleted            {
			get { return _iscompleted; }
		}
		public WaitHandle AsyncWaitHandle {
			get {
				lock(this) {
					if(_callCompleteEvent == null) 
						_callCompleteEvent = new ManualResetEvent(false);
					return _callCompleteEvent;
				}
			}
		}



	}
	class AsyncTextFileRequest
	{
	
	  private AsyncTextFileState _asyncRequestState;
	
	  public AsyncTextFileRequest(AsyncTextFileState ars)
	  {
	    _asyncRequestState = ars;
	  }
	    
	  public void ProcessRequest()
	  {
           string chiave = "";
            string fileName = "";
            byte[] filedati;
            //string FileStreamData = "";
            if (_asyncRequestState._ctx.Request.Params["gid"] == null) {Nulla(); _asyncRequestState.CompleteRequest();return; }

            chiave = _asyncRequestState._ctx.Request.Params["gid"].ToString();
            //FileStreamData = HttpUtility.UrlDecode(HttpContext.Current.Request.Params["dt"].ToString());
//            if (_asyncRequestState._ctx.Cache.Get("DATIFILE" + chiave) == null) { Nulla(); _asyncRequestState.CompleteRequest();return; }
//            if (_asyncRequestState._ctx.Cache.Get("NAMEFILE" + chiave ) == null) { Nulla(); _asyncRequestState.CompleteRequest();return; }
//
//            filedati = (byte[])_asyncRequestState._ctx.Cache.Get("DATIFILE" + chiave);
//            fileName = (string)_asyncRequestState._ctx.Cache.Get("NAMEFILE" + chiave);
//
//            if (fileName.Trim() == "") { Nulla(); _asyncRequestState.CompleteRequest();return; }
//            if (filedati == null) { Nulla(); _asyncRequestState.CompleteRequest();return; }
			
            Function.CacheFileObjectInfo fileInfo = 
            	Function.CacheManager.cachemanager.getCacheFileObjectInfo(_asyncRequestState._ctx,chiave);
            //            	Function.CacheManager.cachemanager.TransmitCacheFileObject(chiave,_asyncRequestState._ctx,false);
            //	_asyncRequestState.CompleteRequest(); return;            	
			if(fileInfo.exists==false || fileInfo.filename.Trim().Length==0) {
				Nulla(_asyncRequestState._ctx,"NO FILE" + 
            	     fileInfo.filename + ", " +
            	     fileInfo.filesize + ", " +
            	     fileInfo.edited + ", " +            	     
            	     fileInfo.exists 
            	     );_asyncRequestState.CompleteRequest(); return;
            }
            Function.CacheManager.cachemanager.TransmitCacheFileObject(chiave,_asyncRequestState._ctx,false);
           	_asyncRequestState.CompleteRequest(); return;  
            /*
			_asyncRequestState._ctx.Response.ContentType = "text/xml";
			_asyncRequestState._ctx.Response.ContentEncoding = System.Text.Encoding.UTF8;
			System.IO.MemoryStream mr = new System.IO.MemoryStream(filedati);
			mr.WriteTo(_asyncRequestState._ctx.Response.OutputStream);
			_asyncRequestState._ctx.Response.End();
			mr.Close();
			mr.Dispose();
			*/
		//finito.
		//_asyncRequestState.CompleteRequest();
	  }
		private void Nulla() { 
            _asyncRequestState._ctx.ApplicationInstance.Response.StatusCode = 404;
            _asyncRequestState._ctx.ApplicationInstance.CompleteRequest();
		}
		private void Nulla(HttpContext corrente, string errore) { 
        	//HttpContext.Current.Response.Clear();
        	corrente.Response.ContentType = "text/html";
        	corrente.Response.Write(errore);
            corrente.Response.End();
		}	  
	  
	}
	
	
}
